package com.struggle.myrabbitmq.sample.subscribe;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.DeliverCallback;
//import com.rabbitmq.client.QueueingConsumer;
import com.struggle.myrabbitmq.sample.MyRabbitConstants;
import com.struggle.myrabbitmq.sample.common.RecvUtil;
import com.struggle.myrabbitmq.util.ConnectionUtil;
import lombok.SneakyThrows;

/**
 * @className Receive1
 * @Description 订阅模式：消费者2
 * @Author liuwj3
 * @Date 2019/9/30 0030 下午 4:38
 **/
public class Receive2 {

    @SneakyThrows
    public static void main(String[] args) throws Exception {
        Connection connection = ConnectionUtil.getConnection();
        Channel channel = connection.createChannel();

        // 声明队列
        channel.queueDeclare(MyRabbitConstants.QUEUE_NAME_SUBSCRIBE_2, false, false , false, null);
        // 绑定队列到交换机上，
        channel.queueBind(MyRabbitConstants.QUEUE_NAME_SUBSCRIBE_2, MyRabbitConstants.EXCHANGE_NAME_FANOUT, "");

        // 同一时刻服务器只会发一条消息给消费者，得到确认才会继续发送
        channel.basicQos(1);

        // rabbitmq 3.4.1版本写法
        /*QueueingConsumer consumer = new QueueingConsumer(channel);
        // 手动确认
        channel.basicConsume(MyRabbitConstants.QUEUE_NAME_SUBSCRIBE_2, false, consumer);

        while (true) {
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            byte[] body = delivery.getBody();
            String message = new String(body);
            System.out.println(" [Recv2] Received '" + message + "'");
            Thread.sleep(10);

            channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
        }*/

        // rabbitmq 4.x版本后写法
        DeliverCallback callback = RecvUtil.getDeliverCallback(channel, "Recv2", true);
        channel.basicConsume(MyRabbitConstants.QUEUE_NAME_SUBSCRIBE_2, false, callback, consumerTag -> {});

    }
}
